package com.sdses.weather.config.mapping;

import lombok.extern.slf4j.Slf4j;

import java.lang.invoke.MethodHandle;
import java.util.Map;

@Slf4j
public class FieldInstruction<T> {
    private final MethodHandle setterHandle;
    private final FieldConverter<Object> converter;
    private final String jsonKey;

    public FieldInstruction(MethodHandle setterHandle, FieldConverter<Object> converter, String jsonKey) {
        this.setterHandle = setterHandle;
        this.converter = converter;
        this.jsonKey = jsonKey;
    }

    public void apply(T instance, Map<String, Object> source, String provider) {
        Object rawValue = source.get(jsonKey);
        if (rawValue == null) return;

        Object converted = converter.convert(rawValue.toString(), provider);
        if (converted != null) {
            try {
                setterHandle.invoke(instance, converted); // ⚡ 高性能调用
            } catch (Throwable e) {
                log.warn("设值失败: {}", jsonKey, e);
            }
        }
    }
}